package com.smart.auth.service;

import cn.hutool.core.collection.CollectionUtil;
import com.smart.core.starter.constant.SecurityConstants;
import com.smart.core.starter.model.R;
import com.smart.core.starter.model.SmartUser;
import com.smart.upms.sys.feign.UserApiClient;
import com.smart.upms.sys.result.SysUserResult;
import com.smart.upms.sys.result.UserInfoResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户信息服务
 *
 * @author guxiaobai
 * @date 2018/12/7 15:50
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final UserApiClient userApiClient;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        R<UserInfoResult> result = userApiClient.info(username);
        return getUserDetails(result);
    }

    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(R<UserInfoResult> result) {
        if (result == null || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserInfoResult info = result.getData();
        Set<String> authSet = new HashSet<>();
        if (CollectionUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            info.getRoles().forEach(role -> authSet.add(SecurityConstants.ROLE + role));
        }
        if (CollectionUtil.isNotEmpty(info.getPermissions())) {
            // 获取资源
            info.getPermissions().forEach(perm -> authSet.add(SecurityConstants.PERM + perm));
        }
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(authSet.toArray(new String[0]));
        SysUserResult user = info.getUserResult();

        // 构造security用户
        return new SmartUser(user.getId(), user.getDeptId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(),
                !user.getDelFlag(), true, true, true, authorities);
    }
}
